<script setup>
import { ref } from 'vue'
import { login } from '@/api/login.js'
import { useRouter } from 'vue-router'
import { userStore } from '@/stores/user.js'
import navBar from '@/components/navBar.vue'
defineOptions({
  name: 'AppLogin'
})
const router = useRouter()
const useUserStore = userStore()
const data = ref({
  username: '',
  password: '',
  agree: true
})
const rule = ref({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  agree: [
    {
      validator(rule, value, callback) {
        if (value) return callback()
        return callback(new Error('请同意用户协议'))
      }
    }
  ]
})
const form = ref(null)
const sub = async () => {
  await form.value.validate()
  const res = await login({
    loginname: data.value.username,
    password: data.value.password
  })
  if (res.data.code == 200) {
    useUserStore.setUserInfo(data.value.username)
    ElMessage.success('登陆成功，即将跳转首页')
    setTimeout(() => router.push('/home'), 1500)
  } else ElMessage.error(res.data.msg)
}
</script>

<template>
  <div class="bg-light vh-100 con">
    <navBar></navBar>
    <div class="box bg-white">
      <div class="row py-5">
        <div class="col-4 d-none d-md-flex offset-2 align-items-center">
          <img src="@/assets/img/login_bg.png" class="d-block w-100" alt="" />
        </div>
        <div class="my-5 col-md-4 col-6 offset-md-0 offset-3">
          <h1 class="mb-4">欢迎登录</h1>
          <el-form ref="form" :model="data" :rules="rule" status-icon>
            <el-form-item label="登录：" prop="username">
              <el-input
                v-model="data.username"
                placeholder="请输入用户名"
              ></el-input> </el-form-item
            ><el-form-item label="密码：" prop="password">
              <el-input
                v-model="data.password"
                placeholder="请输入密码"
                show-password
                type="password"
              ></el-input>
            </el-form-item>
            <el-form-item prop="agree">
              <el-checkbox v-model="data.agree"
                >我已同意阅读登录协议</el-checkbox
              >
            </el-form-item>
            <el-form-item>
              <el-button class="w-100" type="primary" @click="sub"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
          <el-link @click="$router.push('/sign')">没有账号？去注册</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.con {
  overflow: hidden;
}
.box {
  img {
    transition: 0.5s;
    cursor: pointer;
    &:hover {
      transform: translateX(-10px);
    }
  }

  h1 {
    color: #000000;
    cursor: pointer;
  }
}
</style>
